package com.jams.goodox.activity.serve.enterprise;

import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.jams.goodox.BaseActivity;
import com.jams.goodox.R;
import com.jams.goodox.SePref;
import com.jams.goodox.entity.Label;
import com.jams.goodox.entity.resp.LabelsResp;
import com.jams.goodox.listen.DialogActionListener;
import com.jams.goodox.listen.UploadListener;
import com.jams.goodox.net.RetrofitCallbackListener;
import com.jams.goodox.net.services.EnterpriseService;
import com.jams.goodox.utils.CollectionUtils;
import com.jams.goodox.utils.DataCacheManager;
import com.jams.goodox.utils.DeviceUtils;
import com.jams.goodox.utils.EditTextUtils;
import com.jams.goodox.utils.RetrofitUtils;
import com.jams.goodox.utils.StringUtils;
import com.jams.goodox.utils.ToastUtil;
import com.jams.goodox.widget.EditTextWithDel;
import com.jams.goodox.widget.PromptBuilderDialog;
import com.jams.library.commonAdapter.RecycleCommonAdapter;
import com.jams.library.commonAdapter.RecycleCommonViewHolder;
import com.jams.library.listener.OnRecycleItemClickListener;
import com.jams.library.widget.DividerGridItemDecoration;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import butterknife.Bind;
import butterknife.OnClick;
import retrofit2.Call;
import uama.hangzhou.image.photochoose.PhotoChoose;
import uama.hangzhou.image.widget.MyGridView;

import static com.jams.goodox.activity.serve.enterprise.EnterpriseCooperationActivity.RESULT_CODE;


/**
 * 企业合作,发布帖子
 */
public class EnterpriseCooperationPublishActivity extends BaseActivity {


    @Bind(R.id.rcv_innings_publish)
    RecyclerView mRecyclerView;
    @Bind(R.id.et_innings_publish_label)
    EditTextWithDel etInningsPublishLabel;
    @Bind(R.id.et_innings_publish_content)
    EditText etInningsPublishContent;
    @Bind(R.id.gv_innings_publish_photo)
    MyGridView mGridView;
    private RecycleCommonAdapter adapter;
    private int selectPosition;
    private PhotoChoose photoChoose;
    private ProgressDialog progressDialog;
    private TextView tvSend;
    /**
     * 企业合作的label内容,如:"出售设备","求帮忙"
     */
    List<Label> labelList = new ArrayList<>();

    @Override
    protected int getLayoutId() {
        return R.layout.activity_enterprise_cooperation_publish;
    }

    @Override
    protected void init() {
        //title隐藏
        setTitleVisibility(false);
        selectPosition = -1;
        tvSend = (TextView) findViewById(R.id.head_right_tv);
        tvSend.setTextColor(ContextCompat.getColor(mContext, R.color.font_main));
        tvSend.setBackgroundResource(R.drawable.main_theme_radius);
        mRecyclerView.setLayoutManager(new GridLayoutManager(this, 4));
        mRecyclerView.setHasFixedSize(true);
        mRecyclerView.setAdapter(adapter = new RecycleCommonAdapter<Label>(this, labelList, R.layout.item_enterprise_cooperation_publish) {
            @Override
            public void convert(final RecycleCommonViewHolder helper, final Label item, final int position) {
                if (position == selectPosition) {
                    helper.setBackground(R.id.tx_hint, R.drawable.bg_orange_3dp);
                    helper.setTextColor(mContext, R.id.tx_hint, R.color.font_white);
                } else {
                    helper.setBackground(R.id.tx_hint, R.drawable.orange);
                    helper.setTextColor(mContext, R.id.tx_hint, R.color.emphasized_contents);
                }

                helper.setText(R.id.tx_hint, item.getName());
                helper.setOnItemClickListener(new OnRecycleItemClickListener() {
                    @Override
                    public void itemClick() {
                        setLabel(item.getName());
                        selectPosition = position;
                        notifyDataSetChanged();
                    }
                });
            }
        });

        mRecyclerView.addItemDecoration(new DividerGridItemDecoration(mContext, (int) getResources().getDimension(R.dimen.gap_little), ContextCompat.getColor(mContext, R.color.white)));
        photoChoose = new PhotoChoose(this, mGridView, 9);
        getLabels();
    }
    private void publish() {
        tvSend.setClickable(false);
        if (progressDialog == null) {
            progressDialog = ProgressDialog.show(this, "", getString(R.string.submitting), true, false);
        } else {
            progressDialog.show();
        }
        RetrofitUtils.uploadImage(this, photoChoose.getChosenImageList(), "neighbor", new UploadListener() {
            @Override
            public void success(List imageList) {
                progressDialog.dismiss();
                publishContent(imageList);
            }

            @Override
            public void failure() {
                progressDialog.dismiss();
                tvSend.setClickable(true);
            }
        });

    }

    //发布
    private void publishContent(List list) {
        enqueue(createCallService(EnterpriseService.class).publishEnterpriseCooperation(SePref.getCommunityId(), DataCacheManager.getInstance().getUser().getEnterpriseId(), list, etInningsPublishContent.getText().toString().trim(), etInningsPublishLabel.getText().toString().trim()), new RetrofitCallbackListener() {
            @Override
            public void onSuccess(Call call, Object result) {
                progressDialog.dismiss();
                ToastUtil.show(getString(R.string.publish_success));
                setResult(RESULT_CODE);
                finish();
            }

            @Override
            public void onError(String msg) {
                progressDialog.dismiss();
            }
        });
    }

    //设置主题
    private void setLabel(String str) {
        etInningsPublishLabel.setText(str);
        etInningsPublishLabel.setSelection(etInningsPublishLabel.getText().toString().length());
    }

    //检查输入
    private boolean checkInputIsValid() {
        final String hanZi = "[\\u4e00-\\u9fa5]{2,4}";//2到4个中文字符
        Pattern idNumPattern = Pattern.compile(hanZi);
        Matcher idNumMatcher = idNumPattern.matcher(StringUtils.newString(etInningsPublishLabel.getText().toString().trim()));

        if (!idNumMatcher.matches()) {
            ToastUtil.show(this, R.string.tip_label_2_4_words);
            return false;
        } else if (EditTextUtils.editTextIsEmpty(etInningsPublishContent)) {
            ToastUtil.show(this, R.string.tip_words_description);
            return false;
        } else if (photoChoose.getChosenImageList().isEmpty()) {
            ToastUtil.show(this, R.string.select_one_image);
            return false;
        }
        return true;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        photoChoose.setImageList(requestCode, resultCode, data);
    }


    private void checkPageData() {
        DeviceUtils.closeKeyBoard(this);
        if (!EditTextUtils.editTextIsEmpty(etInningsPublishLabel) || !EditTextUtils.editTextIsEmpty(etInningsPublishContent) || !photoChoose.getChosenImageList().isEmpty()) {

            new PromptBuilderDialog(this).setTitle(R.string.tips).setContent(R.string.publish_drop_tips).setPositive(R.string.confirm).setNegative(R.string.cancel).setCancelAble(true).setActionClickListener(new DialogActionListener() {
                @Override
                public void cancel(DialogInterface dialog, int which) {
                    dialog.dismiss();
                }

                @Override
                public void confirm(DialogInterface dialog, int which) {
                    dialog.dismiss();
                    finish();
                }
            }).show();
        } else {
            finish();
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
    }

    @Override
    public void onBackPressed() {
        checkPageData();
    }


    @OnClick({R.id.tv_cancel, R.id.tv_send})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_cancel:
                checkPageData();
                break;
            case R.id.tv_send:
                if (checkInputIsValid()) {
                    publish();
                }
                break;
        }
    }

    /**
     * 发布企业合作帖子的 内容, "出售设备","求帮忙" 从后台获取
     */
    private void getLabels() {
        showLoading();
        enqueue(createCallService(EnterpriseService.class).getLabels(), new RetrofitCallbackListener<LabelsResp>() {
            @Override
            public void onSuccess(Call<LabelsResp> call, LabelsResp result) {
                misLoading();
                try {
                    labelList.clear();
                    labelList.addAll(result.getData());
                    adapter.notifyDataSetChanged();
                    mRecyclerView.setVisibility(CollectionUtils.hasData(labelList)?View.VISIBLE:View.GONE);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onError(String msg) {
                misLoading();
                mRecyclerView.setVisibility(View.GONE);
            }
        });
    }

}
